<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { CreateElement } from 'vue'

@Component({
  name: 'RenderActionItems'
})
export default class extends Vue {
  // current row
  @Prop({ type: Object, required: true })
  private row: any
  // operation buttons
  @Prop({ type: [Array, Object], required: false, default: () => [] })
  private actions: any

  private command (idx: number): void {
    const func = this.actions[idx].event as Function
    func(this.row)
  }

  render (h: CreateElement) {
    const buttons = (this.actions instanceof Array
      ? this.actions
      : [this.actions]
    ).filter(_ => {
      if (typeof _.hide === 'function') {
        return !_.hide(this.row)
      } else {
        return !_.hide
      }
    })

    if (buttons.length > 3) {
      return h(
        'el-dropdown',
        {
          props: { trigger: 'click' },
          on: { command: this.command }
        },
        [
          h('span', { class: 'table-column-dropdown-trigger' }, [
            'click',
            h('i', { class: 'el-icon-arrow-down' })
          ]),
          h(
            'el-dropdown-menu',
            { slot: 'dropdown' },
            buttons.map((btn, idx) =>
              h('el-dropdown-item', { props: { command: idx } }, btn.text)
            )
          )
        ]
      )
    } else {
      return h(
        'div',
        buttons.map((btn, idx) =>
          h(
            'el-button',
            {
              props: { type: 'text' },
              on: {
                click: () => {
                  this.command(idx)
                }
              }
            },
            btn.text
          )
        )
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.table-column-dropdown-trigger {
  font-size: 12px;
  color: $primary;
  cursor: pointer;
}
</style>
